package com.gowiny.ddns.core.handler;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.ArrayUtils;

import com.gowiny.ddns.core.vo.DomainRecord;
import com.gowiny.ddns.core.vo.Manifest;

public abstract class AbstractDdnsHandler implements DdnsHandler {

	protected abstract void init(Manifest manifest);
	@Override
	public void handle(Manifest manifest,DomainRecord domainRecord, Map<String, String> ipInfo) {
		init(manifest);
		String[] hostNames = domainRecord.getHostName().split(";");
		String[] types = domainRecord.getTypes();
		Map<String, String> changedIps;
		if(ArrayUtils.isEmpty(types)) {
			changedIps = ipInfo;
		}else {
			changedIps = new HashMap<String, String>();
			for(String type:types) {
				if(ipInfo.containsKey(type)) {
					changedIps.put(type, ipInfo.get(type));
				}
			}
		}
		for(String hostName:hostNames) {
			for(Entry<String,String> entry:changedIps.entrySet()) {
				String[] arr = hostName.split(":");
				String line = null;
				String host = null;
				if(arr.length > 1) {
					line = arr[0];
					host = arr[1];
				}else {
					host = arr[0];
				}
				handleItem(manifest,domainRecord,host,line,entry.getKey(),entry.getValue());
			}
		}
	}

	protected abstract void handleItem(Manifest manifest,DomainRecord domainRecord,String hostName,String line,String ipType,String ipValue);
	@Override
	public void close() throws Exception {
		
	}
	
	

}
